<?php
declare(strict_types=1);

namespace app\validate;

use think\Validate;

class PackageValidate extends Validate
{
    protected $rule = [
        'id' => 'require|number',
        'package_name' => 'require|max:50',
        'package_price' => 'require|float|gt:0',
        'package_desc' => 'require|max:500',
        'discount_rate' => 'require|float|between:0,100',
        'valid_time' => 'require|integer|gt:0',
        'package_id' => 'require|number'
    ];

    protected $message = [
        'id.require' => '套餐ID不能为空',
        'id.number' => '套餐ID必须为数字',
        'package_name.require' => '请输入套餐名称',
        'package_name.max' => '套餐名称不能超过50个字符',
        'package_price.require' => '请输入套餐价格',
        'package_price.float' => '套餐价格必须为数字',
        'package_price.gt' => '套餐价格必须大于0',
        'package_desc.require' => '请输入套餐描述',
        'package_desc.max' => '套餐描述不能超过500个字符',
        'discount_rate.require' => '请输入折扣率',
        'discount_rate.float' => '折扣率必须为数字',
        'discount_rate.between' => '折扣率必须在0-100之间',
        'valid_time.require' => '请输入有效期',
        'valid_time.integer' => '有效期必须为整数',
        'valid_time.gt' => '有效期必须大于0',
        'package_id.require' => '套餐ID不能为空',
        'package_id.number' => '套餐ID必须为数字'
    ];

    protected $scene = [
        'save' => ['package_name', 'package_price', 'package_desc', 'discount_rate', 'valid_time'],
        'update' => ['id', 'package_name', 'package_price', 'package_desc', 'discount_rate', 'valid_time'],
        'delete' => ['id'],
        'purchase_list' => ['package_id']
    ];

    /**
     * 保存场景扩展验证
     */
    public function sceneSave(): PackageValidate
    {
        return $this->append([
            'package_name' => function($value, $data) {
                // 检查同一商家下套餐名称是否重复
                $exists = \app\model\MemberPackage::where([
                    'merchant_id' => request()->merchant->id,
                    'package_name' => $value
                ]);
                
                if (isset($data['id'])) {
                    $exists = $exists->where('id', '<>', $data['id']);
                }
                
                return !$exists->find();
            }
        ], '该套餐名称已存在');
    }

    /**
     * 更新场景扩展验证
     */
    public function sceneUpdate(): PackageValidate
    {
        return $this->sceneSave();
    }

    /**
     * 删除场景扩展验证
     */
    public function sceneDelete(): PackageValidate
    {
        return $this->append([
            'id' => function($value) {
                // 检查套餐是否存在且属于当前商家
                return \app\model\MemberPackage::where([
                    'id' => $value,
                    'merchant_id' => request()->merchant->id
                ])->find();
            }
        ], '套餐不存在或无权操作');
    }
} 